package com.xianyu.us.common.config;


import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xianyu.us.pojo.vo.JsonResult;

/**
 * 全局异常类，对全局的异常进行的统一处理
 * @author wangshili
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler{
	
	@ExceptionHandler(RuntimeException.class)//只要产生这个异常就会处理，这也是我们继承这个异常的原因
	@ResponseBody
	public JsonResult doHandleRuntimeException(RuntimeException e) {
		e.printStackTrace();//打印异常
		//将异常以json格式的方式发送给浏览器
		//或者改为相关提示信息
		return new JsonResult(e);
	}
	
	//处理shiro异常
	@ExceptionHandler(ShiroException.class)
	@ResponseBody
	public JsonResult doHandleShiroException(ShiroException e) {
		 JsonResult r=new JsonResult();
		 r.setState(0);//设置为0，代表错误
		if(e instanceof UnknownAccountException) {
			r.setMessage("用户不存在");
		}else if(e instanceof LockedAccountException) {
			r.setMessage("用户已被禁用");
		}else if(e instanceof IncorrectCredentialsException) {
			r.setMessage("密码错误");
		}else if(e instanceof AuthorizationException) {
			r.setMessage("没有此操作权限");
		}else {
			r.setMessage("系统维护中");
		}
		e.printStackTrace();
		return r;
	}
}
